package com.dhcc.core.modules.system.controller;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dhcc.core.framework.annotion.BussinessLog;
import com.dhcc.core.framework.annotion.CacheClear;
import com.dhcc.core.framework.annotion.Permission;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.constant.Const;
import com.dhcc.core.framework.constant.state.PermPrincipalType;
import com.dhcc.core.framework.constant.state.ResourceGroup;
import com.dhcc.core.framework.constant.state.ResourceStatus;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.result.node.ZTreeNode;
import com.dhcc.core.framework.util.Bean2MapUtil;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.modules.system.cache.resource.IResourceCache;
import com.dhcc.core.modules.system.cache.resource.ResourceCache;
import com.dhcc.core.modules.system.entity.Resource;
import com.dhcc.core.modules.system.service.IResourceService;
import com.dhcc.core.modules.system.warpper.ResourceWarpper;

/**
 * 前台菜单控制器
 * 
 * @ClassName: ResourceFrontController
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午10:30:13
 */
@Controller
@RequestMapping("${sys.backendPath}/resource_front")
public class ResourceFrontController extends BaseController {

    private static String PREFIX = "/backend/system/resource/front/";

    private static Integer RESOURCE_GROUP = ResourceGroup.FRONT.getCode();

    @Autowired
    IResourceService resourceService;

    /**
     * 跳转到菜单列表列表页面
     */
    @RequestMapping
    public String index() {
        return PREFIX + "resource.html";
    }

    /**
     * 跳转到菜单列表列表页面
     */
    @Permission("front:resource:add")
    @RequestMapping(value = "/resource_add")
    public String resourceAdd() {
        return PREFIX + "resource_add.html";
    }

    /**
     * 跳转到菜单详情列表页面
     */
    @Permission("front:resource:update")
    @RequestMapping(value = "/resource_edit/{resourceId}")
    public String resourceEdit(@PathVariable Long resourceId, Model model) {
        if (CommonUtil.isEmpty(resourceId)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        Resource resource = this.resourceService.selectById(resourceId);

        // 获取父级菜单的id
        Resource pResource = this.resourceService.selectById(resource.getParentId());

        // 如果父级是顶级菜单
        if (pResource == null) {
            resource.setParentId(Const.TREE_ROOT_ID);
        } else {
            // 设置父级菜单的code为父级菜单的id
            resource.setParentId(pResource.getId());
        }

        Map<String, Object> resourceMap = Bean2MapUtil.toMap(resource);
        resourceMap.put("parentName", ResourceCache.me().getResourceNameById(resource.getParentId()));
        model.addAttribute("resource", resourceMap);
        return PREFIX + "resource_edit.html";
    }

    /**
     * 修该菜单
     */
    @Permission("front:resource:update")
    @RequestMapping(value = "/edit")
    @BussinessLog(value = "修改菜单")
    @ResponseBody
    @CacheClear(IResourceCache.CACHE_NAME)
    public R edit(@Valid Resource resource, BindingResult result) {
        if (result.hasErrors()) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        resource.setResGroup(RESOURCE_GROUP);
        resource.init();
        this.resourceService.updateById(resource);
        return R.ok();
    }

    /**
     * 获取菜单列表
     */
    @Permission("front:resource:list")
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String resourceName,
            @RequestParam(required = false) String level) {
        List<Map<String, Object>> resources = this.resourceService.selectResources(RESOURCE_GROUP, resourceName, level);
        return super.warpObject(new ResourceWarpper(resources));
    }

    /**
     * 新增菜单
     */
    @Permission("front:resource:add")
    @RequestMapping(value = "/add")
    @BussinessLog(value = "菜单新增")
    @ResponseBody
    @CacheClear(IResourceCache.CACHE_NAME)
    public R add(@Valid Resource resource, BindingResult result) {
        if (result.hasErrors()) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        resource.setStatus(ResourceStatus.ENABLE.getCode());
        resource.setResGroup(RESOURCE_GROUP);
        resource.init();
        this.resourceService.insert(resource);
        return R.ok();
    }

    /**
     * 删除菜单
     */
    @Permission("front:resource:delete")
    @RequestMapping(value = "/remove")
    @BussinessLog(value = "删除菜单")
    @ResponseBody
    @CacheClear(IResourceCache.CACHE_NAME)
    public R remove(@RequestParam Long resourceId) {
        if (CommonUtil.isEmpty(resourceId)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }

        // 删除资源
        this.resourceService.delResourceContainSubResources(resourceId);

        return R.ok();
    }

    /**
     * 查看菜单
     */
    @RequestMapping(value = "/view/{resourceId}")
    @ResponseBody
    public R view(@PathVariable Long resourceId) {
        if (CommonUtil.isEmpty(resourceId)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        this.resourceService.selectById(resourceId);
        return R.ok();
    }

    /**
     * 获取菜单列表(所有)
     */
    @RequestMapping(value = "/tree")
    @ResponseBody
    public List<ZTreeNode> tree() {
        return ResourceCache.me().getFrontdResourceTree();
    }

    /**
     * 获取角色列表
     */
    @RequestMapping(value = "/treeByRoleId/{roleId}")
    @ResponseBody
    public List<ZTreeNode> resourceTreeListByRoleId(@PathVariable Long roleId) {
        List<Long> resourceIds = this.resourceService.getResourceIdsByPrincipalId(roleId,PermPrincipalType.ROLE.getCode());
        if (CommonUtil.isEmpty(resourceIds)) {
            List<ZTreeNode> roleTreeList = this.resourceService.tree(RESOURCE_GROUP);
            return roleTreeList;
        } else {
            List<ZTreeNode> roleTreeListByUserId = this.resourceService.resourceTreeListByResourceIds(RESOURCE_GROUP,
                    resourceIds);
            return roleTreeListByUserId;
        }
    }

}
